package com.cracker.websocket.server.service;

import com.alibaba.fastjson.JSONObject;
import com.cracker.websocket.server.constant.CmdConstant;
import com.cracker.websocket.server.constant.MessageTypeConstant;
import com.cracker.websocket.server.dao.GroupDao;
import com.cracker.websocket.server.dto.ResponseCmdDto;
import com.cracker.websocket.server.dto.message.GroupMessageDto;
import com.cracker.websocket.server.dto.messagemeta.AudioMessage;
import com.cracker.websocket.server.dto.messagemeta.TextMessage;
import com.cracker.websocket.server.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Service
@Slf4j
public class GroupService {
    @Autowired
    private SessionService sessionService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private GroupDao groupDao;

    public Set<Session> listSessionByGroupId(String groupId) {
        HashSet<Session> sessions = new HashSet<>();
        // 根据群组id查找userID列表
        Set<UserEntity> userEntities = groupDao.listUserById(groupId);
        if (null != userEntities) {
            userEntities.forEach(e -> {
                Session session = sessionService.getByUserId(e.getId());
                if (null != session) {
                    sessions.add(session);
                }
            });
        }
        return sessions;
    }

    public void broadcast(Session session, String groupId, GroupMessageDto messageDto) throws IOException {
        // 处理发送消息类型
        JSONObject dto;
        if (!(messageDto.getMessage() instanceof JSONObject)) {
            dto = JSONObject.parseObject(JSONObject.toJSONString(messageDto.getMessage()));
        } else {
            dto = (JSONObject) messageDto.getMessage();
        }
        switch (messageDto.getMessageType()) {
            case MessageTypeConstant.TEXT:
                TextMessage textMessage = dto.toJavaObject(TextMessage.class);
                messageDto.setMessage(textMessage);
                log.warn("发送文本消息 {}", textMessage);
                break;
            case MessageTypeConstant.AUDIO:
                AudioMessage audioMessage = dto.toJavaObject(AudioMessage.class);
                messageDto.setMessage(audioMessage);
                log.warn("发送语音消息 {}", audioMessage);
                break;
        }
        Set<Session> sessionSet = listSessionByGroupId(groupId);
        if (sessionSet != null) {
            sessionSet.forEach((e) -> {
                if (null == session || !e.getId().equals(session.getId())) {
                    try {
                        e.getBasicRemote().sendText(messageService.encode(messageDto));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
        if (null != session) {
            ResponseCmdDto<GroupMessageDto> responseCmdDto = new ResponseCmdDto<>();
            responseCmdDto.setCmd(CmdConstant.CHATROOM_MSG);
            responseCmdDto.setData(messageDto);
            session.getBasicRemote().sendText(messageService.encode(responseCmdDto));
        }
        // TODO 持久化聊天数据
    }

}
